package com.scalosoft.action.upload;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.validation.SkipValidation;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
@Namespace("/upload")
@Result(name = "success", location = "/upload/UploadImage.jsp")
@InterceptorRefs({ @InterceptorRef("fileUpload"), @InterceptorRef("basicStack") })
public class UploadImage extends ActionSupport implements ServletRequestAware {
	
	private File userImage;
	private String userImageContentType;
	private String userImageFileName;
	private HttpServletRequest servletRequest;
	
	public String backtUrl;
	public String nextUrl;
	
	@Action(value = "Upload")
	@SkipValidation
	public String init() {
		System.out.println("backtUrl:" + backtUrl);
		System.out.println("nextUrl:" + nextUrl);
		return SUCCESS;
	}

	@Action(value = "UploadImage", results = { 
			@Result(name = "success", location = "/upload/UploadImageSuccess.jsp"),
			@Result(name = "redirect", location = "${redirectUrl}", type = "redirect") 
	})
	public String execute() {
		try {
			String filePath = servletRequest.getSession().getServletContext().getRealPath("/upload");
			System.out.println("Server path:" + filePath);
			System.out.println("redirectUrl:" + backtUrl);
			System.out.println("nextUrl:" + nextUrl);
			File fileToCreate = new File(filePath, this.userImageFileName);
			FileUtils.copyFile(this.userImage, fileToCreate);
		} catch (Exception e) {
			e.printStackTrace();
			addActionError(e.getMessage());
			return INPUT;
		}
		if (nextUrl != null && backtUrl!=null)
			return "redirect";
		else
			return SUCCESS;
	}

	public File getUserImage() {
		return userImage;
	}

	public void setUserImage(File userImage) {
		this.userImage = userImage;
	}

	public String getUserImageContentType() {
		return userImageContentType;
	}

	public void setUserImageContentType(String userImageContentType) {
		this.userImageContentType = userImageContentType;
	}

	public String getUserImageFileName() {
		return userImageFileName;
	}

	public void setUserImageFileName(String userImageFileName) {
		this.userImageFileName = userImageFileName;
	}

	@Override
	public void setServletRequest(HttpServletRequest servletRequest) {
		this.servletRequest = servletRequest;

	}
	
}